package com.umessage.hotel.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import com.alibaba.fastjson.JSONObject;
import com.umessage.common.util.Atools;
import com.umessage.hotel.domain.WxCfg;

public class HttpUtil {
	// 发送推送请求
	public static JSONObject sendGet(String URLParam, String bodyParams) {

		JSONObject backJSON = null;
		try {
			final String ADD_URL = URLParam;
			// 创建连接
			URL url = new URL(ADD_URL);// 创建java url对象
			HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();// 创建该对象的https请求
			connection.setDoOutput(true);// 设置请求允许向对方服务器传输
			connection.setDoInput(true);// 设置请求允许己方接收传输
			connection.setRequestMethod("POST");// 设置传输方式POST
			connection.setUseCaches(false);// POST请求不允许设置缓存
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			connection.connect();// 建立链接

			// POST请求
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			if (bodyParams != null) {
				out.write(bodyParams.getBytes("UTF-8"));// 传输中文需要标明转码格式
			}
			out.flush();
			out.close();

			// 读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 接收流
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				sb.append(lines);
			} // 读取返回的数据
			reader.close();
			// 断开连接
			connection.disconnect();
			backJSON = JSONObject.parseObject(sb.toString());
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return backJSON;
	}

	// 获取微信用户信息
	public static JSONObject getWXUserInfo(String code, WxCfg wxcfg) {
		JSONObject backJSON = null;
		//TODO:说明：测试使用
		if("wxxq".equals(code)) {
			backJSON = new JSONObject();
			String openid = Atools.getMD5Code(code);
			backJSON.put("openid", openid);
		} else {
			//正式请使用上面的代码，通过微信接口获取openid
			String URLParam = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxcfg.getAppId() + "" + "&secret=" + wxcfg.getSecretKey()
			+ "&js_code=" + code + "&grant_type=authorization_code";
			
			// 发送 GET 请求
			backJSON = HttpUtil.sendGet(URLParam, null);
		}
		return backJSON;
	}

}
